package cn.itsource.basic.aop;

import cn.itsource.basic.annotation.Repeat;
import cn.itsource.basic.exception.BusinessException;
import cn.itsource.basic.util.RedisService;
import com.sun.org.apache.regexp.internal.RE;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect //声明这是一个切面类
@Component //spring管理
@Slf4j //log可以打印
public class RepeatAop {

    @Autowired
    private RedisService redisService;

    /**
     * 声明切点  : 何地
     */
    @Pointcut("@annotation(repeat)") //只要配置了自定义注解Repeat 的方法就会被匹配到,就会进aop
    public void cut(Repeat repeat){

    }

    /**
     * 何时
     * @param repeat
     */
    @Before("cut(repeat)")
    public void repeat(Repeat repeat){
        //1.获取request对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        log.info("你的名称,{}  {}","王太你吧","sdf");

        //2.获取
        //3.拦截同一个ip一直获取验证码
        String ipPhoneStr = request.getRemoteAddr() + request.getRequestURI();

        //把手机号截取掉
        int i = ipPhoneStr.lastIndexOf("/");

        ipPhoneStr = ipPhoneStr.substring(0,i);

        String res = redisService.getKeyObjectValue(ipPhoneStr, String.class);
        if (res != null){
            throw new BusinessException("兄die,你不正常.111..");
        }
        //存ip到redis中,保持1分钟,1分钟内重复获取抛出上面的异常 默认值
        redisService.setStringKeyAndValue(ipPhoneStr,"123456",repeat.value());

    }

}

